package com.kaoshi.user.config;

import com.kaoshi.common.config.Result;
import com.kaoshi.user.pojo.OperationLog;
import com.kaoshi.user.service.OperationLogService;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Component
@Aspect
public class LogAspect {

    @Resource
    private OperationLogService operationLogService;

    @Around("@annotation(autoLog)")
    public Object doAround(ProceedingJoinPoint joinPoint,AutoLog autoLog) throws Throwable{

        //执行具体的接口
        Result result = (Result) joinPoint.proceed();

        //操作内容
        String name = autoLog.value();
        //操作时间
        LocalDateTime time = LocalDateTime.now();
        //操作人
//        String username = "zs";
        String username = UsernameHolder.getUsername();
        //操作人IP
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getRemoteAddr();


        //再去往日志表添加数据
        OperationLog operationLog = new OperationLog(null, name, time, username, ip);
        operationLogService.add(operationLog);
        return result;
    }
}
